package cn.edu.sdjzu.xg.eagle.entity;


import java.util.List;

/**
 *  Condition类用于 一个查询条件
 *  将前端传递的筛选参数结构化，最终形成 SQL 的 WHERE 字句
 */

public class Condition {

    // 键
    private String key;
    // 值
    private String value;
    // 操作符
    private String operate;

    public Condition() {}

    //构造器
    public Condition(String key, String value, String operate) {
        this.key = key;
        this.value = value;
        this.operate = operate;
    }

    //  处理子句
    public static String toWhereClause(List<Condition> conditionList) {
        if (conditionList == null || conditionList.isEmpty()) {
            return "";
        }
        StringBuffer sb = new StringBuffer("WHERE ");
        for (Condition condition : conditionList) {
            String key = condition.getKey();
            String value = condition.getValue();
            String operate = condition.getOperate().toUpperCase();

            //处理 like 操作符
            if ("LIKE".equals(operate)) {
                value = "‘%" + value + "%’";
            } else if ("=".equals(operate)) {
                if (!isNumeric(value)) {
                    value = "'" + value + "'";
                }
            }
            sb.append(key).append(" ").append(operate).append(" ").append(value).append(" AND");
            if (sb.length() > 0) {
                sb.setLength(sb.length() - 5);
            }
        }
        return sb.toString();
    }

    private static boolean isNumeric(String str) {
        if (str == null && str.isEmpty()) {
            return false;
        }
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    //  转为字符串
    @Override
    public String toString() {
        return "Condition [key=" + key + ", value=" + value + ", operate=" + operate + "]";
    }

    //getter方法
    public String getKey() {
        return key;
    }
    public String getValue() {
        return value;
    }
    public String getOperate() {
        return operate;
    }

    //setter方法
    public void setKey(String key) {
        this.key = key;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public void setOperate(String operate) {
        this.operate = operate;
    }

}
